package ddd.ajava.chapter7.question2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.thoughtworks.xstream.XStream;

public class ObjectToXML {
	public static void main(String[] args){
		Person person=new Person();
		person.setName("ddd");
		person.setAge(23);
		Address address=new Address("chonqqing","Hong Guang Street");
		person.setAddress(address);
		ObjectToXML.writeXML(person);
		
		String packageName=ObjectToXML.class.getPackage().getName().replace(".","\\");
		Person p=(Person)ObjectToXML.readXML("src\\"+packageName+"\\student.xml");
		System.out.println("name:"+p.getName()+",age:"+p.getAge()+",address:"+p.getAddress().getStreet()+" "+p.getAddress().getProvince());
		
	}
	public static void writeXML(Object obj){
		try{
			String packageName=ObjectToXML.class.getPackage().getName().replace(".","\\");
			BufferedWriter bw=new BufferedWriter(new FileWriter("src\\"+packageName+"\\student.xml"));
			XStream xstream=new XStream();
			String serialvalue=xstream.toXML(obj);
			bw.newLine();
			bw.write(serialvalue);
			bw.newLine();
			bw.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static Object readXML(String filePath){
		Object obj=null;
		try{
			BufferedReader br=new BufferedReader(new FileReader(filePath));
			XStream xstream=new XStream();
			obj=xstream.fromXML(br);
			return obj;
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}
		return obj;
	}
}
